package cn.tj.wenda.cloud.client;

import cn.tj.wenda.cloud.entity.ResponseBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 服务降级通用代理类
 * wenda
 * 2018年10月6日
 */
public class FallbackProxy implements InvocationHandler {
		
	private Throwable _cause = null;
	private Logger _logger = null;
	private String _serviceName = "";
	 
	@SuppressWarnings("rawtypes")
	public static Object newInstance(String serviceName,Class clazz,Throwable cause) {
		Class[] interfaces = new Class[]{
			clazz
		};
		Logger logger = LoggerFactory.getLogger(clazz);
	    return Proxy.newProxyInstance(FallbackProxy.class.getClassLoader(),
	        interfaces, new FallbackProxy(serviceName,cause,logger));
	} 
 
	private FallbackProxy(String serviceName, Throwable cause, Logger logger) {
		this._cause = cause;
		this._logger = logger;
		this._serviceName = serviceName;
	} 

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		this._logger.error("服务【" + this._serviceName + "】已暂时停用，原因：",this._cause);
		
		if(method.getReturnType() != ResponseBean.class ) {
			return null;
		}

		ResponseBean res = new ResponseBean();
        res.setErr("1");
        res.setErrMsg("服务【" + this._serviceName + "】暂时不能访问，请稍候再试。");
        return res;

	}

}
